package com.ldk.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.base.framework.util.SystemUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.factory.MenuExt;
import com.ldk.admin.factory.MenuFactory;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.framework.entity.Menu;
import com.ldk.framework.service.IMenuService;

@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController {
	
	private String route = "menu";
	private String module = "菜单管理";

	
	@Autowired
	private IMenuService menuService;
	
	
	@RequestMapping("/list")
	public ModelAndView list(ModelMap map, HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		if (this.getRoleId(request) == 6) {
			setLinks(map, "", "", module, "/"+route+"/list", "", "");
		} else {
			setLinks(map, "", "", module, "/"+route+"/list", "添加"+module, "/"+route+"/add");
		}

		//操作日志
		//this.insertOplog(request,module,"","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

		if (this.getRoleId(request) == 6) {
			return new ModelAndView("/menu/listmenu_sj");
		} else {
			return new ModelAndView("/menu/listmenu");
		}
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<Menu> getList(@RequestParam(value="page",required=false,defaultValue="1") int page, 
			            @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
			            @RequestParam(value="menuName",required=false,defaultValue="") String menuName,
			            HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;
		
		Menu query = new Menu();
		query.setParentId(-1);
		query.setEnabled(null);
		if(!StringUtils.isEmpty(menuName)){
			query.setMenuName(menuName);
		}
		
		CustomPageable pageable = new CustomPageable(offset, limit);
		Page<Menu> result = menuService.selectPageList("", query, pageable);
		
		LigerUIGridResult<Menu> grid = new LigerUIGridResult<>();
		grid.Total = result.getTotalElements();
		grid.Rows = result.getContent();
		
		return grid;
	}
	
	@ResponseBody
	@RequestMapping("/getMenus")
	public List<MenuExt> getMenus(){
		Menu query = new Menu();
		query.setParentId(-1);
		query.setEnabled(true);
		
		List<Menu> menus = menuService.selectList("", query);
		
		MenuFactory factory = new MenuFactory();
		List<MenuExt> menuExts = factory.build(menus);
		
		return menuExts;
	}
	
	@RequestMapping("/add")
	public ModelAndView add(ModelMap map, HttpServletRequest request,
							HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		
		setLinks(map, module+"管理", "/"+route+"/list", "添加"+module, "/"+route+"/add", "", "");
		setForm(map, "/"+route+"/insert", null);
		
		Menu menu = new Menu();
		
		return new ModelAndView("/menu/menuinfo","model",menu);
	}
	
	@RequestMapping("/edit/{menuId}")
	public ModelAndView edit(@PathVariable int menuId, ModelMap map, HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		Menu query = new Menu();
		query.setMenuId(menuId);
		
		Menu menu = menuService.selectByKey("", query);
		if(menu == null){
			return new ModelAndView("redirect:/menu/list");
		}
		
		setLinks(map, module+"管理", "/"+route+"/list", "编辑"+module, "/"+route+"/edit/"+menuId, "", "");
		setForm(map, "/menu/update", null);
		
		
		return new ModelAndView("/menu/menuinfo","model", menu);
	}
	
	@RequestMapping("/insert")
	public ModelAndView insert(@ModelAttribute("model") Menu model, RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		
		try{
			if(model.getEnabled() == null){
				model.setEnabled(true);
			}

			//操作日志
			this.insertOplog(request,module,"","","添加菜单:"+model.getMenuName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

		    Boolean succeed = menuService.addMenu("", model);
		    if(succeed){
		    	rst.AddOk("添加"+module+"成功");
		    }
		    else{
		    	rst.AddError("添加"+module+"失败");
		    }
		}
		catch(Exception e){
			logger.error(e.getMessage());
			rst.AddError("添加"+module+"失败");
		}
		
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		return new ModelAndView("redirect:/"+route+"/add");
	}
	
	@RequestMapping("/update")
	public ModelAndView update(@ModelAttribute("model") Menu model, RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		
		try{
			if(model.getEnabled() == null){
				model.setEnabled(true);
			}

			//操作日志
			this.insertOplog(request,module,"","","修改菜单:"+model.getMenuName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

			Boolean succeed = menuService.updateMenu("", model);
		    if(succeed){
		    	rst.AddOk("修改"+module+"成功");
		    }
		    else{
		    	rst.AddError("修改"+module+"失败");
		    }
		}
		catch(Exception e){
			logger.error(e.getMessage());
			rst.AddError("修改菜单失败");
		}

		redAttr.addAttribute("menuId", model.getMenuId());
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		return new ModelAndView("redirect:/"+route+"/edit/{menuId}");
	}
	
	@ResponseBody
	@RequestMapping("/remove/{menuId}")
	public ResponseResult remove(@PathVariable int menuId, HttpServletRequest request){
		
		ResponseResult rst = new ResponseResult();
		if(menuId < 1)
		{
			rst.AddError("删除"+module+"错误");
		}
		Boolean succeed = false;
		try{
			Menu query = new Menu();
			query.setMenuId(menuId);
			Menu menu = menuService.selectByKey("", query);
			//操作日志
			this.insertOplog(request,module,"","","删除菜单:"+menu.getMenuName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

			succeed = menuService.deleteMenu("", menuId);
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(succeed){
			rst.AddOk("删除"+module+"成功");
		}
		else{
			rst.AddError("删除"+module+"失败");
		}
		
		return rst;
	}
}
